import React, { useEffect, useState, useCallback } from 'react';
import {
  Box,
  Container,
  Alert,
  Snackbar,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Typography,
} from '@mui/material';
import { useParams, useNavigate } from 'react-router-dom';
import { useSocket } from '@/hooks/useSocket';
import { useWebRTC } from '@/hooks/useWebRTC';
import { useMediaDevices } from '@/hooks/useMediaDevices';
import { roomApi } from '@/services/api';
import { getUserId, saveRecentRoom } from '@/utils/helpers';
import { ERROR_MESSAGES } from '@/utils/constants';
import VideoContainer from './VideoContainer';
import ControlPanel from './ControlPanel';
import ParticipantsList from './ParticipantsList';
import RoomInfo from './RoomInfo';
import Loading from '../common/Loading';

const RoomPage: React.FC = () => {
  const { roomId } = useParams<{ roomId: string }>();
  const navigate = useNavigate();
  
  const [isInitializing, setIsInitializing] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showLeaveDialog, setShowLeaveDialog] = useState(false);
  const [notification, setNotification] = useState<string | null>(null);
  
  // Hooks
  const {
    isConnected,
    isInRoom,
    participants,
    error: socketError,
    connect,
    disconnect,
    joinRoom,
    leaveRoom,
  } = useSocket();
  
  const {
    localStream,
    remoteStream,
    connectionState,
    isAudioEnabled,
    isVideoEnabled,
    error: webrtcError,
    initializeMedia,
    createOffer,
    createAnswer,
    addIceCandidate,
    toggleAudio,
    toggleVideo,
    hangup,
  } = useWebRTC();
  
  const {
    devices,
    currentDevices,
    hasPermission,
    isLoading: devicesLoading,
    error: devicesError,
    requestPermission,
    switchDevice,
  } = useMediaDevices();

  // 初始化房间
  const initializeRoom = useCallback(async () => {
    if (!roomId) {
      setError('房间ID无效');
      return;
    }

    try {
      setIsInitializing(true);
      
      // 检查房间是否存在
      const roomExists = await roomApi.checkRoom(roomId);
      if (!roomExists.exists) {
        setError('房间不存在或已过期');
        return;
      }

      // 请求媒体权限
      const permissionGranted = await requestPermission();
      if (!permissionGranted) {
        setError('需要摄像头和麦克风权限才能加入通话');
        return;
      }

      // 初始化媒体流
      await initializeMedia();
      
      // 连接Socket
      await connect();
      
      // 保存到最近访问记录
      saveRecentRoom(roomId);
      
      setNotification('正在加入房间...');
    } catch (error: any) {
      console.error('初始化房间失败:', error);
      setError(error.message || ERROR_MESSAGES.UNKNOWN_ERROR);
    } finally {
      setIsInitializing(false);
    }
  }, [roomId, requestPermission, initializeMedia, connect]);

  // 加入房间
  const handleJoinRoom = useCallback(async () => {
    if (!roomId || !isConnected) return;
    
    try {
      const userId = getUserId();
      await joinRoom(roomId, userId);
      setNotification('成功加入房间');
    } catch (error: any) {
      console.error('加入房间失败:', error);
      setError(error.message || ERROR_MESSAGES.UNKNOWN_ERROR);
    }
  }, [roomId, isConnected, joinRoom]);

  // 离开房间
  const handleLeaveRoom = useCallback(async () => {
    try {
      await leaveRoom();
      hangup();
      disconnect();
      navigate('/');
    } catch (error: any) {
      console.error('离开房间失败:', error);
      // 即使出错也要导航回首页
      navigate('/');
    }
  }, [leaveRoom, hangup, disconnect, navigate]);

  // 处理挂断
  const handleHangup = useCallback(() => {
    setShowLeaveDialog(true);
  }, []);

  // 确认离开
  const confirmLeave = useCallback(() => {
    setShowLeaveDialog(false);
    handleLeaveRoom();
  }, [handleLeaveRoom]);

  // 取消离开
  const cancelLeave = useCallback(() => {
    setShowLeaveDialog(false);
  }, []);

  // 处理设备切换
  const handleDeviceSwitch = useCallback(async (deviceType: 'audioinput' | 'videoinput' | 'audiooutput', deviceId: string) => {
    try {
      await switchDevice(deviceType, deviceId);
      // 如果切换的是音视频输入设备，需要重新初始化媒体流
      if (deviceType === 'audioinput' || deviceType === 'videoinput') {
        await initializeMedia();
      }
    } catch (error: any) {
      console.error('切换设备失败:', error);
      setError('切换设备失败');
    }
  }, [switchDevice, initializeMedia]);

  // 初始化
  useEffect(() => {
    initializeRoom();
    
    // 清理函数
    return () => {
      hangup();
      disconnect();
    };
  }, []);

  // 自动加入房间
  useEffect(() => {
    if (isConnected && !isInRoom && localStream) {
      handleJoinRoom();
    }
  }, [isConnected, isInRoom, localStream, handleJoinRoom]);

  // 错误处理
  useEffect(() => {
    if (socketError) {
      setError(socketError);
    }
  }, [socketError]);

  useEffect(() => {
    if (webrtcError) {
      setError(webrtcError);
    }
  }, [webrtcError]);

  useEffect(() => {
    if (devicesError) {
      setError(devicesError);
    }
  }, [devicesError]);

  // 页面卸载时清理
  useEffect(() => {
    const handleBeforeUnload = () => {
      handleLeaveRoom();
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [handleLeaveRoom]);

  // 加载状态
  if (isInitializing) {
    return (
      <Container maxWidth="lg" sx={{ height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Loading message="正在初始化房间..." size={64} />
      </Container>
    );
  }

  // 错误状态
  if (error) {
    return (
      <Container maxWidth="lg" sx={{ height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Alert
          severity="error"
          action={
            <Button color="inherit" size="small" onClick={() => navigate('/')}>
              返回首页
            </Button>
          }
        >
          {error}
        </Alert>
      </Container>
    );
  }

  return (
    <Container maxWidth="lg" sx={{ height: '100vh', display: 'flex', flexDirection: 'column', py: 2 }}>
      {/* 房间信息 */}
      <RoomInfo
        roomId={roomId!}
        participants={participants}
        connectionState={connectionState}
      />

      {/* 主要内容区域 */}
      <Box sx={{ flex: 1, display: 'flex', gap: 2, minHeight: 0 }}>
        {/* 视频容器 */}
        <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
          <VideoContainer
            localStream={localStream}
            remoteStream={remoteStream}
            isAudioEnabled={isAudioEnabled}
            isVideoEnabled={isVideoEnabled}
            participants={participants}
          />
          
          {/* 控制面板 */}
          <ControlPanel
            isAudioEnabled={isAudioEnabled}
            isVideoEnabled={isVideoEnabled}
            connectionState={connectionState}
            devices={devices}
            currentDevices={currentDevices}
            onToggleAudio={toggleAudio}
            onToggleVideo={toggleVideo}
            onHangup={handleHangup}
            onDeviceSwitch={handleDeviceSwitch}
          />
        </Box>

        {/* 参与者列表 */}
        <ParticipantsList
          participants={participants}
          currentUserId={getUserId()}
        />
      </Box>

      {/* 离开房间确认对话框 */}
      <Dialog
        open={showLeaveDialog}
        onClose={cancelLeave}
        aria-labelledby="leave-dialog-title"
      >
        <DialogTitle id="leave-dialog-title">
          确认离开房间
        </DialogTitle>
        <DialogContent>
          <Typography>
            您确定要离开当前的视频通话吗？
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={cancelLeave} color="primary">
            取消
          </Button>
          <Button onClick={confirmLeave} color="error" variant="contained">
            离开
          </Button>
        </DialogActions>
      </Dialog>

      {/* 通知消息 */}
      <Snackbar
        open={!!notification}
        autoHideDuration={3000}
        onClose={() => setNotification(null)}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert onClose={() => setNotification(null)} severity="info">
          {notification}
        </Alert>
      </Snackbar>
    </Container>
  );
};

export default RoomPage;